<template>
  <div class="consultation-manage">
    <!-- 标题 -->
    <div class="title">重点关注个案</div>

    <!-- 查询区域 -->
    <div class="search-bar">
      <el-select
        v-model="selectedYear"
        placeholder="请选择年份"
        class="search-select"
      >
        <el-option
          v-for="year in yearOptions"
          :key="year"
          :label="year"
          :value="year"
        />
      </el-select>
      <el-select
        v-model="selectedGrade"
        placeholder="全部等级"
        class="search-select"
      >
        <el-option
          v-for="grade in gradeOptions"
          :key="grade"
          :label="grade"
          :value="grade"
        />
      </el-select>
      <el-input
        v-model="searchKey"
        placeholder="请输入学生姓名/学号关键词查询"
        class="search-input"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" @click="showAddDialog('添加关注')">添加关注</el-button>
      <el-button type="primary" @click="handleExport">数据导出</el-button>
    </div>

    <!-- 主表格区域（重点关注个案列表） -->
    <el-table
      ref="mainTableRef"
      :data="paginatedMainData"
      border
      style="width: 100%"
      class="consultation-table"
      header-cell-class-name="table-header"
      @selection-change="handleMainSelectionChange"
      row-key="studentId"
      :expand-row-keys="expandRowKeys"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="index" label="序号" width="70" />
      <el-table-column prop="riskLevel" label="风险等级">
        <template #default="scope">
          <span :class="riskLevelClass(scope.row.riskLevel)">
            {{ scope.row.riskLevel }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="studentName" label="学生姓名" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="account" label="账号/工号" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="counselor" label="责任辅导员" />
      <el-table-column prop="consultCount" label="咨询次数" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleViewRecord(scope.row)"
          >查看记录</el-button>
          <el-button
            type="text"
            @click="handleMoreOperation(scope.row)"
          >更多</el-button>
        </template>
      </el-table-column>
      <!-- 展开行：咨询记录子表格 -->
      <el-table-column type="expand">
        <template #default="scope">
          <el-table
            :data="scope.row.consultRecords"
            border
            style="width: 100%"
            class="sub-table"
          >
            <el-table-column prop="consultIndex" label="序号" width="70" />
            <el-table-column prop="consultProblem" label="咨询问题" />
            <el-table-column prop="consultPlace" label="咨询地点" />
            <el-table-column prop="consultTime" label="咨询时间" />
            <el-table-column prop="consultStatus" label="咨询状态" />
            <el-table-column prop="reserveStatus" label="预约状态" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column label="操作" width="100">
              <template #default="subScope">
                <el-button
                  type="text"
                  @click="handleViewRealTime(subScope.row)"
                >查看实时详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量操作和分页 -->
    <div class="bottom-bar">
      <div class="pagination-info">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="totalMainData"
        />
      </div>
    </div>

    <!-- 添加关注抽屉 -->
    <el-drawer v-model="dialogFormVisible" direction="rtl">
      <template #header>
        <h4>{{titleName}}</h4>
      </template>
      <template #default>
        <el-form ref="form" :model="formData"  label-position="top" :rules="rules">
          <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="studentName">
            <el-input v-model="formData.studentName" autocomplete="off" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio label="男性">男性</el-radio>
              <el-radio label="女性">女性</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="账号/工号" :label-width="formLabelWidth" prop="account">
            <el-input v-model="formData.account" autocomplete="off" placeholder="请输入账号/工号" />
          </el-form-item>
          <el-form-item label="联系电话" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="formData.phone" autocomplete="off" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="责任辅导员" :label-width="formLabelWidth" prop="counselor">
            <el-input v-model="formData.counselor" autocomplete="off" placeholder="请输入责任辅导员" />
          </el-form-item>
          <el-form-item label="风险等级" :label-width="formLabelWidth" prop="riskLevel">
            <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
              <el-option label="校级关怀" value="校级关怀"></el-option>
              <el-option label="院级关怀" value="院级关怀"></el-option>
              <el-option label="普通关怀" value="普通关怀"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addFocusCase()">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { faker } from '@faker-js/faker';

const router = useRouter();

// 年份筛选
const yearOptions = ['2023', '2024', '2025'];
const selectedYear = ref('2024');
// 等级筛选
const gradeOptions = ['全部等级', '校级关怀', '院级关怀', '普通关怀'];
const selectedGrade = ref('全部等级');
// 搜索关键词
const searchKey = ref('');
// 主表格数据
const originalMainData = ref<Array<any>>([]);
// 随机生成姓名的函数
const generateRandomName = () => {
  const firstNames = ['赵', '钱', '孙', '李', '周', '吴', '郑', '王'];
  const lastNames = ['伟', '芳', '娜', '敏', '静', '强', '磊', '军'];
  const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
  const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
  return firstName + lastName;
};

// 随机生成账号的函数
const generateRandomAccount = () => {
  const min = 10000;
  const max = 99999;
  return Math.floor(Math.random() * (max - min + 1) + min).toString();
};

// 随机生成电话号码的函数
const generateRandomPhone = () => {
  const prefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139'];
  const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
  const suffix = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  return prefix + suffix;
};

// 模拟生成主表格数据（含子表格咨询记录）
const generateMockMainData = (count: number) => {
  const data = [];
  for (let i = 0; i < count; i++) {
    const consultRecords = [];
    // 随机生成 1 - 3 条咨询记录
    const recordCount = Math.floor(Math.random() * 3) + 1;
    for (let j = 0; j < recordCount; j++) {
      consultRecords.push({
        consultIndex: j + 2,
        consultProblem: j === 0 ? '恋爱' : (j === 1 ? '其他' : '学习'),
        consultPlace: j === 0 ? '南湖校区心理中心204' : (j === 1 ? '南湖校区心理中心306' : '南湖校区心理中心512'),
        consultTime: j === 0 ? '8:30 - 11:30' : (j === 1 ? '15:30 - 18:30' : '12:00 - 15:30'),
        consultStatus: j === 0 ? '排号中' : (j === 1 ? '咨询中' : '咨询结束'),
        reserveStatus: j === 0 ? '已预约' : (j === 1 ? '未预约' : '正在预约'),
        updateTime: '2025/07/6 13:30:05'
      });
    }
    data.push({
      index: i + 1,
      studentId: `student_${i + 1}`,
      riskLevel: ['校级关怀', '院级关怀', '普通关怀'][Math.floor(Math.random() * 3)],
      studentName: generateRandomName(),
      gender: ['女', '男'][Math.floor(Math.random() * 2)],
      account: generateRandomAccount(),
      phone: generateRandomPhone(),
      counselor: ['胡凌郡', '许坐', '黄杰'][Math.floor(Math.random() * 3)],
      consultCount: recordCount,
      consultRecords
    });
  }
  return data;
};
originalMainData.value = generateMockMainData(5);

// 筛选后的数据
const filteredMainData = ref([...originalMainData.value]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalMainData = computed(() => filteredMainData.value.length);
// 展开行控制
const expandRowKeys = ref<Array<string>>([]);

// 计算分页后的数据
const paginatedMainData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredMainData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  let filtered = originalMainData.value.filter((item) => {
    const nameMatch = item.studentName.includes(searchKey.value);
    const accountMatch = item.account.includes(searchKey.value);
    return nameMatch || accountMatch;
  });
  // 年份筛选
  if (selectedYear.value) {
    filtered = filtered.filter((item) => {
      // 这里简单模拟，实际可根据数据里的年份字段匹配
      return true;
    });
  }
  // 等级筛选
  if (selectedGrade.value!== '全部等级') {
    filtered = filtered.filter((item) => item.riskLevel === selectedGrade.value);
  }
  filteredMainData.value = filtered;
  currentPage.value = 1;
  expandRowKeys.value = [];
};

// 重置
const handleReset = () => {
  selectedYear.value = '2024';
  selectedGrade.value = '全部等级';
  searchKey.value = '';
  originalMainData.value = generateMockMainData(5);
  filteredMainData.value = [...originalMainData.value];
  currentPage.value = 1;
  expandRowKeys.value = [];
};

// 每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 主表格选中项变化
const handleMainSelectionChange = (rows) => {
  console.log('主表格选中行：', rows);
};

// 风险等级样式
const riskLevelClass = (level: string) => {
  const map: { [key: string]: string } = {
    '校级关怀': 'risk-level-school',
    '院级关怀': 'risk-level-college',
    '普通关怀': 'risk-level-normal'
  };
  return map[level] || '';
};

// 查看记录（跳转到 NewRecord.vue）
const handleViewRecord = (row: any) => {
  router.push({
    name: 'NewRecord',
    params: {
      studentId: row.studentId,
      studentName: row.studentName,
      gender: row.gender,
      account: row.account,
      phone: row.phone,
      counselor: row.counselor,
      riskLevel: row.riskLevel,
      consultCount: row.consultCount,
      // 如果需要传递更多字段，可以在这里添加
    }
  });
};

// 更多操作（可扩展逻辑）
const handleMoreOperation = (row: any) => {
  ElMessageBox.alert(
    `更多操作逻辑可扩展，当前行数据：${JSON.stringify(row)}`,
    '提示',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  );
};

// 查看实时详情（子表格操作）
const handleViewRealTime = (row: any) => {
  ElMessageBox.alert(
    `实时详情逻辑可扩展，当前子行数据：${JSON.stringify(row)}`,
    '提示',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  );
};

// 抽屉相关
const dialogFormVisible = ref(false);
const titleName = ref('');
const form = ref(null);
const formLabelWidth = '140px';
const formData = ref({
  studentName: '',
  gender: '男性',
  account: '',
  phone: '',
  counselor: '',
  riskLevel: '校级关怀'
});

const rules = {
  studentName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '请输入账号/工号', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
  ],
  counselor: [
    { required: true, message: '请输入责任辅导员', trigger: 'blur' },
  ],
  riskLevel: [
    { required: true, message: '请选择风险等级', trigger: 'change' },
  ]
};

const showAddDialog = (title: string) => {
  titleName.value = title;
  resetFormData();
  dialogFormVisible.value = true;
};

const resetFormData = () => {
  formData.value = {
    studentName: '',
    gender: '男性',
    account: '',
    phone: '',
    counselor: '',
    riskLevel: '校级关怀'
  };
};

// 添加关注
const addFocusCase = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      const newId = originalMainData.value.length + 1;
      const consultRecords = [];
      const recordCount = Math.floor(Math.random() * 3) + 1;
      for (let j = 0; j < recordCount; j++) {
        consultRecords.push({
          consultIndex: j + 1,
          consultProblem: j === 0 ? '恋爱':'其他',
          consultPlace: j === 0 ? '南湖校区心理中心204' : '南湖校区心理中心306',
          consultTime: j === 0 ? '8:30-11:30' : '15:30-18:30',
          consultStatus: j === 0 ? '排号中' : '咨询中',
          reserveStatus: j === 0 ? '已预约' : '未预约',
          updateTime: '2025/07/6 13:30:05'
        });
      }
      const newCase = {
        index: newId,
        studentId: `student_${newId}`,
        ...formData.value,
        consultCount: recordCount,
        consultRecords
      };
      originalMainData.value.push(newCase);
      handleSearch();
      dialogFormVisible.value = false;
      ElMessage.success('添加关注成功');
    }
  });
};

// 数据导出
const handleExport = () => {
  const csvData = [
    ['序号', '风险等级', '学生姓名', '性别', '账号/工号', '联系电话', '责任辅导员', '咨询次数'],
    ...filteredMainData.value.map((item) => [
      item.index,
      item.riskLevel,
      item.studentName,
      item.gender,
      item.account,
      item.phone,
      item.counselor,
      item.consultCount
    ])
  ];
  const csvContent = csvData.map((row) => row.join(',')).join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', 'focus_cases.csv');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped lang="scss">
.consultation-manage {
  padding: 20px;
  background-color: #fff;

  .title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 16px;
  }

  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .search-select {
      width: 150px;
      margin-right: 10px;
    }

    .search-input {
      width: 250px;
      margin-right: 10px;
    }
  }

  .consultation-table {
    margin-bottom: 16px;

    .table-header {
      background-color: #f5f7fa;
      color: #666;
    }

    .risk-level-school {
      color: red;
    }
    .risk-level-college {
      color: orange;
    }
    .risk-level-normal {
      color: #409eff;
    }
  }

  .sub-table {
    margin-top: 10px;
    .el-table__header {
      background-color: #f9f9f9;
    }
  }

  .bottom-bar {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .pagination-info {
      display: flex;
      align-items: center;
    }
  }
}
</style>